<?php
$scheduleData = '[{"start_time":"08:45","interval":1,"courses":["音乐欣赏"]},{"start_time":"13:30","interval":4,"courses":["音乐欣赏"]}]'; //每门课的时间段start_time是开始时间，interval多少节，courses什么课程

// 解析 JSON 数据为 PHP 数组
$periods = json_decode($scheduleData, true);

// 默认参数
$courseCount = 30; // 每门课要排课的数量
$requiredDays = ['2025-01-28', '2025-01-29', '2025-01-30']; // 必排日期
$forbiddenDays = ['2025-01-31']; // 禁排日期
$weekday = [2, 3, 4]; // 周二、周三、周四
$classesPerWeek = 5; // 每周课程数
$classtime = 90; // 每节课时长（分钟）
$classsleeptime = 10; // 课间休息时间（分钟）
$daytime = 3; // 每天最多安排课程数

// 初始化排课表
$schedule = array();

// 计算每周需要排课的总节数
$lessonsPerWeek = 0;
foreach ($periods as $period) {
    if (!in_array($period['start_time'], $requiredDays) && !in_array($period['start_time'], $forbiddenDays)) {
        $lessonsPerWeek += $period['interval'];
    }
}
$lessonsPerWeekTotal = ceil($courseCount / (5)); // 每周最多排课节数：5天 * 3节课/天

// 随机生成排课表
while ($courseCount > 0) {
    $possiblePeriods = array();
    foreach ($periods as $period) {
        if (!in_array($period['start_time'], $requiredDays) && !in_array($period['start_time'], $forbiddenDays)) {
            $availableLessons = count(array_filter($period['courses'], function($course) use ($schedule) {
                return !in_array($course, $schedule);
            }));
            if ($availableLessons > 0) {
                $possiblePeriods[] = $period;
            }
        }
    }

    if (!empty($possiblePeriods)) {
        $randomPeriod = $possiblePeriods[mt_rand(0, count($possiblePeriods) - 1)];
        $availableCourses = array_filter($randomPeriod['courses'], function($course) use ($schedule) {
            return !in_array($course, $schedule);
        });

        if (!empty($availableCourses)) {
            $randomCourse = $availableCourses[array_rand($availableCourses)];
            $lesson = count(array_filter($schedule, function($s) use ($randomPeriod) {
                    return $s['period'] == $randomPeriod['start_time'];
                })) + 1;

            $start_time = date('H:i', strtotime($randomPeriod['start_time'] . ' + ' . (($lesson - 1) * ($classtime + $classsleeptime)) . ' minutes'));
            $end_time = date('H:i', strtotime($randomPeriod['start_time'] . ' + ' . (($lesson - 1) * ($classtime + $classsleeptime) + $classtime) . ' minutes'));

            $schedule[] = array(
                'date' => date('Y-m-d'), // 当前日期
                'period' => $randomPeriod['start_time'], // 每天时间段
                'lesson' => $lesson, // 第几次节课
                'class' => '班级名称', // 班级名称
                'course' => $randomCourse, // 课程名称
                'start_time' => $start_time, // 每节课的开始时间
                'end_time' => $end_time // 每节课的结束时间
            );
            $courseCount--;
        }
    } else {
        break; // 如果没有可排的课程，退出循环
    }
}

// 按照lesson的时间顺序排序
usort($schedule, function($a, $b) {
    return strtotime($a['start_time']) - strtotime($b['start_time']);
});

// 输出结果
print_r($schedule);
?>
